#include "DS1302.h"

//对端口重新定义,位变量，只进行逻辑判断，非零即真
sbit DS1302_CE   = P1^3;
sbit DS1302_IO   = P2^3;
sbit DS1302_SCLK = P1^7;

#define DS1302_SECOND   0x80	//秒
#define DS1302_MINTUE   0x82	//分钟
#define DS1302_HOUR     0x84	//小时
#define DS1302_DATE     0x86	//日
#define DS1302_MONTH    0x88	//月
#define DS1302_DAY      0x8A	//星期
#define DS1302_YEAR     0x8C	//年
#define DS1302_WP       0x8E	//写保护的

unsigned char DS1302_Time[9]={23,2,9,23,59,55,4};//年 月 日 时 分 秒 星期

//上电默认1，先初始化为0
void DS1302_Init(void)
{   
	DS1302_CE    = 0;	//
	DS1302_SCLK  = 0;
}

//单字节写(命令字，数据)
void DS1302_WriteByte(unsigned char Command, unsigned char Data)
{
	unsigned char i;
	DS1302_CE = 1;	
	for (i = 0; i < 8; i ++)	//写命令字
	{
		DS1302_IO = Command & (0x01<<i);
		DS1302_SCLK = 1;
		DS1302_SCLK = 0;
	}
	for (i = 0; i < 8; i ++)	//写数据
	{
		DS1302_IO = Data & (0x01<<i);
		DS1302_SCLK = 1;
		DS1302_SCLK = 0;
	}	
	DS1302_CE = 0;	
}

//单字节读，用上面的宏定义即可
unsigned char DS1302_ReadByte(unsigned char Command)
{
	unsigned char Data = 0x00;
	unsigned char i;
	Command |= 0x01;//变成读的地址
	
	DS1302_CE = 1;	
	for (i = 0; i < 8; i ++)	//写命令字
	{
		DS1302_IO = Command & (0x01<<i);
		DS1302_SCLK = 0;	//先给0后给1，因为时序图上少一个脉冲
		DS1302_SCLK = 1;
	}
	for (i = 0; i < 8; i ++)
	{
		DS1302_SCLK = 1;	//先给1后给0,模拟时序图
		DS1302_SCLK = 0;
		if(DS1302_IO == 1)	//读取端口是1
		{ Data |= (0x01<<i); }	//读数据操作
	}
	DS1302_CE = 0;	
	DS1302_IO = 0;	//修改的地方
	return Data;	
}

void DS1302_SetTime(void)
{
	DS1302_WriteByte(DS1302_WP, 0x00);//解除芯片写保护
	DS1302_WriteByte(DS1302_YEAR,   DS1302_Time[0]/10*16+DS1302_Time[0]%10);//十进制转BCD码
	DS1302_WriteByte(DS1302_MONTH,  DS1302_Time[1]/10*16+DS1302_Time[1]%10);	
	DS1302_WriteByte(DS1302_DATE,   DS1302_Time[2]/10*16+DS1302_Time[2]%10);
	DS1302_WriteByte(DS1302_HOUR,   DS1302_Time[3]/10*16+DS1302_Time[3]%10);
	DS1302_WriteByte(DS1302_MINTUE, DS1302_Time[4]/10*16+DS1302_Time[4]%10);
	DS1302_WriteByte(DS1302_SECOND, DS1302_Time[5]/10*16+DS1302_Time[5]%10);
	DS1302_WriteByte(DS1302_DAY,    DS1302_Time[6]/10*16+DS1302_Time[6]%10);	//星期
	DS1302_WriteByte(DS1302_WP, 0x80);//此句WP给0x80，打开芯片写保护
}

void DS1302_ReadTime(void) //此函数读取时钟芯片的数据，写到数组DS1302_Time里
{
	unsigned char Temp;
	Temp = DS1302_ReadByte(DS1302_YEAR);//进去就被 或运算 置1，变成读，读BCD码
	DS1302_Time[0] = Temp/16*10+Temp%16;	
	Temp = DS1302_ReadByte(DS1302_MONTH);//月
	DS1302_Time[1] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_DATE);
	DS1302_Time[2] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_HOUR);
	DS1302_Time[3] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_MINTUE);
	DS1302_Time[4] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_SECOND);
	DS1302_Time[5] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_DAY);
	DS1302_Time[6] = Temp/16*10+Temp%16;
}


